<template>
    <a-card style="padding: 0px">
        <a-form-model
                hide-required-mark
                ref="companyForm"
                :model="companyForm"
                :rules="companyFormRules"
                :wrapperCol="wrapperCol"
                :label-col="labelCol"
        >

            <a-form-model-item hasFeedback class="form-item" label="法人姓名" prop="legalPerson">
                <a-input v-model="companyForm.legalPerson" class="form-input"/>
            </a-form-model-item>
            <a-form-model-item hasFeedback class="form-item" label="邮箱" prop="email">
                <a-input v-model="companyForm.email" class="form-input"></a-input>
            </a-form-model-item>
            <a-form-model-item hasFeedback class="form-item" label="密码" prop="password">
                <a-input-password v-model="companyForm.password" class="form-input"></a-input-password>
            </a-form-model-item>
            <a-form-model-item hasFeedback class="form-item" label="确认密码" prop="checkPassword">
                <a-input-password v-model="companyForm.checkPassword" class="form-input"></a-input-password>
            </a-form-model-item>

            <a-form-model-item class="form-item" label="身份证类型" prop="idCardType">
                <a-select v-model="companyForm.idCardType" class="form-input">
                    <a-select-option value="1">二代身份证</a-select-option>
                    <a-select-option value="0">临时身份证</a-select-option>
                </a-select>
            </a-form-model-item>

            <a-form-model-item class="form-item" label="法人身份证号" prop="idNumber">
                <a-input v-model="companyForm.idNumber" class="form-input"></a-input>
            </a-form-model-item>

            <a-form-model-item class="form-item" label="法人身份证正面照" v-if="companyForm.fillType==='1'">
                <up-load
                        :common-upload="true"
                        :fieldlName="uploadFieldData.idUrlFront"
                        :image-url="companyForm.idUrlFront"
                        @change-image-url="changeAndSetUrl"
                ></up-load>
            </a-form-model-item>
            <a-form-model-item class="form-item" label="法人身份证背照" v-if="companyForm.fillType==='1'">
                <up-load
                        :common-upload="true"
                        :fieldlName="uploadFieldData.idUrlBack"
                        :image-url="companyForm.idUrlBack"
                        @change-image-url="changeAndSetUrl"
                ></up-load>
            </a-form-model-item>


            <a-form-model-item class="form-item" label="企业名称" prop="companyName">
                <a-input v-model="companyForm.companyName" class="form-input"></a-input>
            </a-form-model-item>
            <a-form-model-item class="form-item" label="社会信用代码" prop="socialCode">
                <a-input v-model="companyForm.socialCode" class="form-input"></a-input>
            </a-form-model-item>
            <a-form-model-item class="form-item" label="归属地" prop="legalPlace">
                <a-select v-model="companyForm.legalPlace" class="form-input">
                    <a-select-option value="1">中国大陆</a-select-option>
                    <a-select-option value="2">中国香港</a-select-option>
                    <a-select-option value="3">中国澳门</a-select-option>
                    <a-select-option value="4">中国台湾</a-select-option>
                </a-select>
            </a-form-model-item>
            <a-form-model-item class="form-item" label="营业执照" prop="businessLicense">
                <up-load
                        :common-upload="true"
                        :fieldlName="uploadFieldData.businessLicense"
                        :image-url="companyForm.businessLicense"
                        @change-image-url="changeAndSetUrl"
                ></up-load>
            </a-form-model-item>


            <a-form-model-item class="form-item" label="开户行" prop="subBankId">
                <a-cascader
                        :field-names="{ label: 'name', value: 'id', children: 'children' }"
                        :options="provinceData"
                        :show-search="{ filterBank }"
                        placeholder="请选择开户行"
                        @change="onBankChange"

                />
            </a-form-model-item>
            <a-form-model-item class="form-item" label="银行开户人姓名" prop="accountHolder">
                <a-input v-model="companyForm.accountHolder" class="form-input"></a-input>
            </a-form-model-item>
            <a-form-model-item class="form-item" label="对公银行账号" prop="bankNumber">
                <a-input v-model="companyForm.bankNumber" class="form-input"></a-input>
            </a-form-model-item>
            <a-form-model-item class="form-item" label="对公手机号" prop="mobile">
                <a-input v-model="companyForm.mobile" class="form-input"></a-input>
            </a-form-model-item>
            <a-form-model-item class="form-item" label="填写人身份" prop="fillType">
                <a-select v-model="companyForm.fillType" class="form-input">
                    <a-select-option value="1">法人本人</a-select-option>
                    <a-select-option value="0">代理人</a-select-option>
                </a-select>
            </a-form-model-item>
            <a-form-model-item v-if="!applyBrand" class="form-item" label="企业品牌绑定" prop="brand">
                <a-select v-model="companyForm.brand.id" class="form-input" show-search
                          option-filter-prop="children"
                          :filter-option="filterOption"

                >
                    <a-select-option v-for="brand in brandData" :value="brand.id">{{brand.name}}</a-select-option>
                </a-select>
                <span @click="applyBrand=true"><a>没有您的品牌？</a></span>

            </a-form-model-item>
            <a-form-model-item v-if="applyBrand" class="form-item" label="品牌申请" prop="brand">
                <a-input v-model="companyForm.brand.name" class="form-input"></a-input>
            </a-form-model-item>
            <a-form-model-item v-if="applyBrand" class="form-item" label="品牌Logo上传" prop="brand">
                <up-load
                        :common-upload="true"
                        :fieldlName="uploadFieldData.brand"
                        :image-url="companyForm.brand.logo"
                        @change-image-url="changeAndSetUrl"
                ></up-load> <span style="color: red;font-size: 12px">（非必须）</span>
            </a-form-model-item>
            <a-form-model-item v-if="companyForm.fillType==='0'" class="form-item" label="代理人身份证正面">
                <up-load
                        :common-upload="true"
                        :fieldlName="uploadFieldData.proxyUserFront"
                        :image-url="companyForm.proxyUserFront"
                        @change-image-url="changeAndSetUrl"
                ></up-load>
            </a-form-model-item>
            <a-form-model-item v-if="companyForm.fillType==='0'" class="form-item" label="代理人身份证背面">
                <up-load
                        :common-upload="true"
                        :fieldlName="uploadFieldData.proxyUserBack"
                        :image-url="companyForm.proxyUserBack"
                        @change-image-url="changeAndSetUrl"
                ></up-load>
            </a-form-model-item>
            <a-form-model-item v-if="companyForm.fillType==='0'" class="form-item" label="委托书">
                <up-load
                        :common-upload="true"
                        :fieldlName="uploadFieldData.comission"
                        :image-url="companyForm.comission"
                        @change-image-url="changeAndSetUrl"
                ></up-load>
            </a-form-model-item>

            <a-form-model-item label="验证码" prop="code">
                <a-input
                        v-model="companyForm.code"
                        style="width: 100%"
                        @blur="handleCodeBlur"
                ></a-input>
                <a-button type="primary" @click="fetchCode" :disabled="!isStop">{{sendcodeMsg}}</a-button>
            </a-form-model-item>
            <a-form-model-item>
                <a-button style="width: 200px" type="primary" @click="handleSubmit('companyForm')">注册</a-button>
            </a-form-model-item>
        </a-form-model>

    </a-card>
</template>

<script>


    import loginApi from "../../../api/login";
    import userApi from "../../../api/user/userApi";
    import UpLoad from "../../../components/upload/UpLoad";
    import bankApi from "../../../api/user/bankApi";
    import {isEmail} from "../../../utils/validate";
    import brandApi from "../../../api/goods/brandApi";
    import verifyApi from "../../../api/user/account/verifyApi";
    import companyApi from "../../../api/user/companyApi";
    import addressApi from "../../../api/info/addressApi";

    export default {
        name: "memberRegister",
        components: {UpLoad},
        data() {
            let validateRawPwd = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请输入密码'));
                } else if (value.length < 4 || value.length > 12) {
                    callback(new Error('密码长度应在4到12位之间'));
                } else {
                    callback();
                }
            };
            let validatePwdCheck = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请输入确认密码'));
                } else if (value !== this.companyForm.password) {
                    callback(new Error("两次输入密码不一致"));
                } else {
                    callback();
                }
                console.log(value)

            };
            let validPhone = (rule, value, callback) => {
                if (!/^1[3456789]\d{9}$/.test(value)) {
                    return callback(new Error("手机号格式不正确"));
                } else {
                    callback();
                }
            };
            let validEmail = (rule, value, callback) => {
                if (!isEmail(value)) {
                    return callback(new Error("邮箱格式不正确"));
                } else {
                    callback();
                }
            };
            return {
                isStop: true, //是否倒计时结束
                sendcodeMsg: "获取验证码", //发送验证码按钮文字
                confirmDirty: false,
                code: "", //验证码
                companyForm: {
                    email: "",
                    password: "",
                    checkPassword: "",
                    legalPerson: "",
                    idNumber: "",
                    companyName: "",
                    socialCode: "",
                    legalPlace: "1",
                    businessLicense: "",
                    idUrlFront: "",
                    idUrlBack: "",
                    idCardType: "1",
                    accountHolder: "",
                    subBankId: "",
                    bankNumber: "",
                    mobile: "",
                    fillType: "1",
                    proxyUserFront: "",
                    proxyUserBack: "",
                    comission: "",
                    code: "",
                    brand: {
                        id: null,
                        name: "",
                        logo: ""
                    }
                },
                uploadFieldData: {
                    idUrlFront: "idUrlFront",
                    idUrlBack: "idUrlBack",
                    proxyUserFront: "proxyUserFront",
                    proxyUserBack: "proxyUserBack",
                    comission: "comission",
                    businessLicense: "businessLicense",
                    brand: "brand"
                },
                companyFormRules: {
                    email: [
                        {required: true, message: '请填写企业邮箱', trigger: 'blur'},
                        {validator: validEmail, trigger: 'blur'}
                    ],
                    password: [
                        {required: true, message: '请填写密码', trigger: 'blur'},
                        {validator: validateRawPwd, trigger: 'change'}
                    ],
                    checkPassword: [
                        {required: true, message: '请填写确认密码', trigger: 'blur'},
                        {validator: validatePwdCheck, trigger: 'blur'}
                    ],
                    legalPerson: [
                        {required: true, message: '请填写企业法人', trigger: 'blur'}
                    ],
                    idNumber: [
                        {required: true, message: '请填写企业法人', trigger: 'blur'}
                    ],
                    companyName: [
                        {required: true, message: '请填写企业名称', trigger: 'blur'}
                    ],
                    socialCode: [
                        {required: true, message: '请填写社会信用代码', trigger: 'blur'}
                    ],
                    legalPlace: [
                        {required: true, message: '请选择企业归属地', trigger: 'change'}
                    ],
                    businessLicense: [
                        {required: true, message: '请上传营业执照', trigger: 'change'}
                    ],
                    accountHolder: [
                        {required: true, message: '请填写银行开户人', trigger: 'blur'}
                    ], subBankId: [
                        {required: true, message: '请选择开户银行', trigger: 'change'}
                    ],
                    bankNumber: [
                        {required: true, message: '请选择开户银行账号', trigger: 'blur'}
                    ],

                    mobile: [
                        {required: true, message: '请填写对公手机号', trigger: 'blur'},
                        {validator: validPhone, trigger: 'blur'}
                    ],
                    code: [
                        {required: true, message: '请填写验证码', trigger: 'blur'}
                    ]
                },
                labelCol: {span: 4},
                wrapperCol: {span: 10},
                provinceData: [],
                brandData: [],
                applyBrand: false,//是否申请品牌
            };
        },
        beforeCreate() {
            this.form = this.$form.createForm(this, {name: 'register'});
        },
        created() {
            this.loadBrand();

            this.loadBankData();
        },
        methods: {
            loadBankData() {
                bankApi.bankData().then(resp => {
                    if (resp.data.flag) {

                        this.provinceData = resp.data.data
                    }
                })
            },
            loadBrand() {
                brandApi.list().then(resp => {
                    if (resp.data.flag) {
                        this.brandData = resp.data.data
                    }
                })
            },
            handleSubmit(formName) {
                this.$refs[formName].validate(valid => {
                    if (valid) {
                        if (this.companyForm.fillType === "1") {
                            if (this.companyForm.idUrlFront.trim() === "" || this.companyForm.idUrlBack.trim()==="") {
                                this.$message.warning("请上传法人身份证件")
                                return;
                            }
                        } else {
                            if (this.companyForm.proxyUserBack.trim() === "" || this.companyForm.proxyUserFront.trim() === "" || this.companyForm.comission.trim() === "") {
                                this.$message.warning("请将代理人证件与委托书上传完整");
                                return;
                            }
                        }
                        if (this.companyForm.businessLicense.trim() === "") {
                            this.$message.warning("请上传营业执照");
                            return;
                        }
                        console.log(this.companyForm)
                        companyApi.register(this.companyForm).then(resp => {
                            if (resp.data.flag) {
                                this.$router.push("/")
                                this.$message.success(resp.data.message)
                            }
                        })

                    } else {
                        console.log('error submit!!');
                        return false;
                    }
                });
            },
            /**
             * 获取验证码
             */
            fetchCode() {
                const email = this.companyForm.email
                if (!email || email.trim() === "") {
                    this.$message.warning("请先填写企业邮箱");
                    return;
                } else if (!isEmail(email)) {
                    this.$message.warning("邮箱格式不正确");
                    return;
                }

                companyApi.checkEmail(email).then(resp => {
                    if (resp.data.flag && resp.data.data === true) {
                        let seconds = 10;
                        this.isStop = false;

                        const that = this; //在setInterval中，this不是vue实例，需要使用that转一下
                        verifyApi.emailCode(email, false).then(resp => {
                            if (resp.data.flag) {
                                this.$message.success(resp.data.message, 1);
                                let id = setInterval(function () {
                                    that.sendcodeMsg = seconds + "秒后可再次获取";
                                    if (seconds === 0) {
                                        clearInterval(id);
                                        that.sendcodeMsg = "点击获取验证码";
                                        that.isStop = true;
                                    }
                                    seconds--;
                                }, 1000);
                            } else {
                                that.sendcodeMsg = "点击获取验证码";
                                that.isStop = true;
                            }
                        });
                    } else {
                        this.$message.warning("该邮箱已被注册，如非您本企业操作，请联系网站人员");
                    }
                })

            },

            changeAndSetUrl(field, url) {
                console.log(field, url)
                let fieldName = field + ''
                switch (fieldName) {
                    case this.uploadFieldData.idUrlFront:
                        this.companyForm.idUrlFront = url;
                        break;
                    case this.uploadFieldData.idUrlBack:
                        this.companyForm.idUrlBack = url;
                        break;
                    case this.uploadFieldData.proxyUserFront:
                        this.companyForm.proxyUserFront = url;
                        break;
                    case this.uploadFieldData.proxyUserBack:
                        this.companyForm.proxyUserBack = url;
                        break;
                    case this.uploadFieldData.comission:
                        this.companyForm.comission = url;
                        break;
                    case this.uploadFieldData.businessLicense:
                        this.companyForm.businessLicense = url;
                        break;
                    case this.uploadFieldData.brand:
                        this.companyForm.brand.logo = url;
                        break;
                    default:
                        break;
                }
            },
            handleConfirmBlur(e) {
                const value = e.target.value;
                this.confirmDirty = this.confirmDirty || !!value;
            },
            /**
             * 校验手机号
             */

            /**
             * 注册时验证码离焦事件
             */
            handleCodeBlur(e) {
                this.code = e.target.value;
            },
            onBankChange(value) {
                console.log(value);
                this.companyForm.subBankId = value[2]
                console.log(this.companyForm)
            },
            filterBank(inputValue, path) {
                return path.some(option => option.label.toLowerCase().indexOf(inputValue.toLowerCase()) > -1);
            },
            filterOption(input, option) {
                return (
                    option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
                );
            },


        },
    };
</script>
<style scoped>

    .form-input {
        width: 400px;
    }

</style>